import 'dart:async';

import 'package:custom_pop_up_menu/custom_pop_up_menu.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ionicons/ionicons.dart';
import 'package:orginone/components/XImage/XImage.dart';
import 'package:orginone/components/Tip/ToastUtils.dart';
import 'package:orginone/components/EntityWidget/EntityInfoDialog.dart';
import 'package:orginone/dart/base/common/commands.dart';
import 'package:orginone/dart/base/common/emitter.dart';
import 'package:orginone/dart/base/model.dart';
import 'package:orginone/dart/base/schema.dart';
import 'package:orginone/dart/base/storages/hive_utils.dart';
import 'package:orginone/dart/base/storages/storage.dart';
import 'package:orginone/dart/core/provider/auth.dart';
import 'package:orginone/dart/core/chat/activity.dart';
import 'package:orginone/dart/core/chat/session.dart';
import 'package:orginone/dart/core/public/consts.dart';
import 'package:orginone/dart/core/public/enums.dart';
import 'package:orginone/dart/core/target/base/target.dart';
import 'package:orginone/dart/core/target/person.dart';
import 'package:orginone/dart/core/thing/fileinfo.dart';
import 'package:orginone/dart/core/thing/standard/index.dart';
import 'package:orginone/dart/core/thing/standard/page.dart';
import 'package:orginone/dart/core/provider/index.dart';
import 'package:orginone/dart/core/work/box.dart';
import 'package:orginone/dart/core/work/provider.dart';
import 'package:orginone/main.dart';
import 'package:orginone/routers/index.dart';
import 'package:orginone/utils/log/log_util.dart';
import 'package:orginone/utils/string_util.dart';
import 'package:orginone/utils/system/PermissionUtil.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../components/XDialogs/XDialog.dart';
import '../../components/XDialogs/dialog_utils.dart';
import '../../pages/portal/assets_management/assets_module/asset_select_modal.dart';
import '../../pages/portal/assets_management/logic.dart';
import '../core/target/base/belong.dart';
import 'app_start_controller.dart';

enum Shortcut {
  addPerson("添加朋友", Icons.group_add_outlined),
  addGroup("加入群组", Icons.speaker_group_outlined),
  createCompany("创建单位", Icons.compare_outlined),
  addCompany("加入单位", Icons.compare_outlined),
  addCohort("发起群聊", Icons.chat_bubble_outline_outlined),
  createDir("新建目录", Ionicons.folder_sharp),
  createApplication("新建应用", Ionicons.apps_sharp),
  createSpecies("新建分类", Ionicons.pricetag_sharp),
  createDict("新建字典", Ionicons.book_sharp),
  createAttr("新建属性", Ionicons.snow_sharp),
  createThing("新建实体配置", Ionicons.pricetag_sharp),
  createWork("新建事项配置", Ionicons.pricetag_sharp),
  uploadFile("上传文件", Ionicons.file_tray_sharp),
  addAppTemp("添加应用模板", Icons.group_add_outlined),
  addDataTemp("添加数据模板", Icons.speaker_group_outlined),
  addShareTemp("添加共享模板", Icons.compare_outlined),
  addDealTemp("添加交易模板", Icons.compare_outlined),
  addCustomPage("添加定制页面", Icons.chat_bubble_outline_outlined);

  final String label;
  final IconData icon;

  const Shortcut(this.label, this.icon);
}

enum SettingEnum {
  // security("账号与安全", XImage.accountSetting),
  // TODO 上架IOS临时注释
  // cardbag("卡包设置", Ionicons.card_outline),
  collection("收藏", XImage.coll),
  // gateway("门户设置", XImage.homeSetting),
  // theme("主题设置", XImage.paletteSetting),
  // vsrsion("版本记录", Ionicons.rocket_outline),
  edit("个人信息", XImage.settingOutline),
  errorLog("错误日志", XImage.fileOutline),
  about("关于奥集能", XImage.informationCircleSetting),
  exitLogin("退出登录", XImage.exit);

  final String label;
  final String icon;

  const SettingEnum(this.label, this.icon);
}

class ShortcutData {
  Shortcut shortcut;
  TargetType? targetType;
  String title;
  String hint;

  ShortcutData(
    this.shortcut, [
    this.title = '',
    this.hint = '',
    this.targetType,
  ]);
}

/// 设置控制器
class IndexController with EmitterMixin {
  ///未使用
  String currentKey = "";

  // /// 用户加载事件订阅
  // StreamSubscription<UserLoaded>? _userSub;

  // /// 事件发射器
  // late Emitter emitter;

  /// 数据提供者
  static DataProvider _provider = DataProvider();

  /// 数据提供者
  DataProvider get data {
    try {
      IndexController._provider;
    } catch (e) {
      IndexController._provider = DataProvider();
    }
    return IndexController._provider;
  }

  /// 数据提供者
  DataProvider get provider => data;

  /// 当前用户
  IPerson? get user => provider.user;

  /// 办事提供者
  IWorkProvider get work => provider.work!;

  /// 所有相关的用户
  List<ITarget> get targets => provider.targets;

  /// 首页当前模块枚举
  var homeEnum = HomeEnum.door.obs;

  ///内核是否在线
  // RxBool isConnected = false.obs;
  late AppStartController appStartController;

  ///用户头像菜单控制器
  late CustomPopupMenuController functionMenuController;

  ///模块顶部三点菜单控制器
  @Deprecated("旧参数，不建议使用")
  late CustomPopupMenuController settingMenuController;

  ///群动态
  @Deprecated("旧参数，不建议使用")
  Rxn<GroupActivity> cohortActivity = Rxn<GroupActivity>();

  ///好友圈
  Rxn<GroupActivity> friendsActivity = Rxn<GroupActivity>();
  int _warpUnderwayCount = 0;

  /// 授权方法
  AuthProvider get auth {
    return provider.auth;
  }

  var menuItems = [
    ShortcutData(
      Shortcut.addPerson,
      "添加好友",
      "请输入用户的账号",
      TargetType.person,
    ),
    ShortcutData(Shortcut.addGroup, "加入群组", "请输入群组的编码", TargetType.cohort),
    ShortcutData(Shortcut.createCompany, "创建单位", "", TargetType.company),
    ShortcutData(
        Shortcut.addCompany, "加入单位", "请输入单位的社会统一代码", TargetType.company),
    ShortcutData(Shortcut.addCohort, "发起群聊", "请输入群聊信息", TargetType.cohort),
  ];

  var menuTemplateItems = [
    ShortcutData(
      Shortcut.addAppTemp,
      "添加应用模版",
      "请输入",
      TargetType.company,
    ),
    ShortcutData(Shortcut.addDataTemp, "添加数据模板", "请输入", TargetType.company),
    ShortcutData(Shortcut.addShareTemp, "添加共享模板", "请输入", TargetType.company),
    ShortcutData(Shortcut.addDealTemp, "添加交易模板", "请输入", TargetType.company),
    ShortcutData(Shortcut.addCustomPage, "添加定制页面", "请输入", TargetType.company),
  ];

  Future<void> onInit() async {
    appStartController = AppStartController();
    functionMenuController = CustomPopupMenuController();
    settingMenuController = CustomPopupMenuController();
    // // // 监听消息加载
    // emitter.subscribe((key, args) {
    //   // loadChats();
    // }, false);
    // _provider = UserProvider();
  }

  /// 暂存提供者
  IBoxProvider? get box {
    return provider.box;
  }

  /// 加载空间下置顶常用
  Future<List<IFileInfo>> loadCommonsTops([IBelong? belong]) async {
    List<IFileInfo> files = [];
    belong = belong ?? user?.currentSpace;
    List<ITarget> targets =
    belong?.id == user?.id ? data.targets : belong?.targets ?? [];
    if (null != belong) {
      for (var item in belong.commons) {
        if (item.typeName == '应用' || item.typeName == '视图' || item.typeName == '商城模板') {
          var target = targets.firstWhereOrNull(
                (i) => i.id == item.targetId && i.spaceId == item.spaceId,
          );
          if (null != target) {
            var file = await target.directory.searchComment(item);
            if (null != file) {
              if (file.groupTags.contains('已删除')) {
                belong.updateCommon(item, false);
              } else {
                files.add(file);
              }
            }
          }
        }
      }
      // relationCtrl.data.home?.cacheCommons.clear();
      // relationCtrl.data.home?.cacheCommons.update(belong.id, (value) => files);
    }
    return files;
  }

  /// 加载空间下所有常用
  Future<List<IFileInfo>> loadCommonsOther([IBelong? belong]) async {
    List<IFileInfo> files = [];
    belong = belong ?? user?.currentSpace;
    List<ITarget> targets =
        belong?.id == user?.id ? data.targets : belong?.targets ?? [];
    if (null != belong) {
      for (var item in belong.commons) {
        var target = targets.firstWhereOrNull(
          (i) => i.id == item.targetId && i.spaceId == item.spaceId,
        );
        if (null != target) {
          var file = await target.directory.searchComment(item);
          if (null != file) {
            if (file.groupTags.contains('已删除')) {
              belong.updateCommon(item, false);
            } else {
              files.add(file);
            }
          }
        }
      }
      // relationCtrl.data.home?.cacheCommons.clear();
      // relationCtrl.data.home?.cacheCommons.update(belong.id, (value) => files);
    }
    return files;
  }

  /// 加载所有常用
  Future<List<IFileInfo<XEntity>>> loadCommons() async {
    List<IFileInfo> files = [];
    List<ITarget> targets = user?.currentSpace.targets ?? [];
    for (var item in relationCtrl.user!.commons) {
      var target = targets.firstWhereOrNull(
            (i) => i.id == item.targetId && i.spaceId == item.spaceId,
      );
      if (null != target) {
        var file = await target.directory.searchComment(item);
        if (null != file) {
          // if (file.groupTags.contains('已删除')) {
          //   belong.updateCommon(item, false);
          // } else {
          files.add(file);
          // }
        }
      }
    }
    return files;
  }

  ISession? findSession(String id) {
    return user?.chats.firstWhereOrNull((element) => element.id == id);
  }

  ISession? findMemberChat(String id, String belongId) {
    ISession? session;
    if (belongId == provider.user?.id) {
      provider.user?.findMemberChat(id);
    }
    for (var company in provider.user!.companys ?? []) {
      if (company.id != belongId) continue;
      session = company.findMemberChat(id);
      if (null != session) {
        break;
      }
    }

    return session;
  }

  /// 过滤和排序消息
  List<ISession> filterAndSortChats(List<ISession> chats) {
    chats = chats
        .where((element) =>
            element.chatdata.lastMessage != null || element.chatdata.recently)
        .toList();

    /// 排序
    chats.sort((a, b) {
      var num = 0;
      if (b.chatdata.lastMsgTime == a.chatdata.lastMsgTime) {
        num = b.isBelongPerson ? 1 : -1;
      } else {
        num = b.chatdata.lastMsgTime > a.chatdata.lastMsgTime ? 5 : -5;
      }
      return num;
    });

    return chats;
  }

  /// 订阅变更
  /// [callback] 变更回调
  /// 返回订阅ID
  @override
  String subscribe(void Function(String, List<dynamic>?) callback,
      [bool? target = true]) {
    return _provider.subscribe(callback, _provider.inited && target!);
  }

  @override
  void unsubscribe([dynamic key]) {
    _provider.unsubscribe(key);
  }

  // Future<List<IApplication>> loadCurrentspaceApplications() async {
  //   List<IApplication> apps = [];
  //   for (var directory in targets
  //       .where(
  //           (i) => i.session.isMyChat && i.typeName != TargetType.group.label)
  //       .map((a) => a.directory)
  //       .toList()) {
  //     apps.addAll((await directory.loadAllApplication()));
  //   }
  //   return apps;
  // }

  Future<List<IApplication>> loadApplications() async {
    List<IApplication> apps = [];
    for (var directory in targets
        .where(
            (i) => i.session.isMyChat && i.typeName != TargetType.group.label)
        .map((a) => a.directory)
        .toList()) {
      apps.addAll((await directory.loadAllApplication()));
    }
    return apps;
  }

  Future<List<IPageTemplate>> loadPages() async {
    List<IPageTemplate> pages = [];
    for (var directory in targets.map((a) => a.directory).toList()) {
      List<IPageTemplate> iPage = await directory.loadAllTemplate();
      for (var element in iPage) {
        if (element.metadata.public) pages.add(element);
      }
    }
    return pages;
  }

  ///获得指定的应用应用
  Future<IApplication?> findApplicationByappId(String appid) async {
    List<IApplication> applications = await loadApplications();
    applications
        .where((element) =>
    element.metadata.id == appid &&
    !element.groupTags.contains("已删除") &&
        element.directory.target.typeName != DirectoryType.storage.label)
        .toSet()
        .toList();
    IApplication? res = applications.firstWhereOrNull((element) => element.id == appid);
    return res;
  }

  ///获得指定的应用应用
  Future<IApplication?> findApplicationById(String xappid) async {
    List<IApplication> applications = await loadApplications();
    applications
        .where((element) =>
    // element.metadata.id == xappid &&
    !element.groupTags.contains("已删除") &&
        element.directory.target.typeName != DirectoryType.storage.label)
        .toSet()
        .toList();
    IApplication? res = applications.firstWhereOrNull((element) => element.id == xappid);
    return res;
  }

  ///获得默认应用
  Future<IApplication?> findApplication() async {
    List<IApplication> applications = await loadApplications();
    applications
        .where((element) =>
            // element.name == "资产管理" &&
            !element.groupTags.contains("已删除") &&
            element.directory.target.typeName != DirectoryType.storage.label)
        .toSet()
        .toList();

    IApplication? res;

    XApplication? cacheApp = await relationCtrl.user!.cacheObj
        .get<XApplication>('assetmodule', XApplication.fromJson);
    if (null != cacheApp) {
      res =
          applications.firstWhereOrNull((element) => element.id == cacheApp.id);
    }
    return res ?? applications.firstOrNull;
  }

  ///更新默认应用
  Future<bool> setApplication(IApplication application) async {
    bool res = await relationCtrl.user!.cacheObj
        .set('assetmodule', application.metadata);
    command.emitterFlag('switchApplication');
    return Future(() => res);
  }

  ///获得默认页面模版
  Future<IPageTemplate?> findPageTemplate() async {
    IPageTemplate? iPageTemplate;
    List<IPageTemplate> iPages = await loadPages();
    XPageTemplate? cachePages = await relationCtrl.user!.cacheObj
        .get<XPageTemplate>('pagetemplatemodule', XPageTemplate.fromJson);
    if (cachePages != null) {
      iPageTemplate =
          iPages.firstWhereOrNull((element) => element.id == cachePages.id);
    }
    return iPageTemplate ?? iPages.firstOrNull;
  }

  ///设置默认页面模版
  Future<bool> setPageTemplate(IPageTemplate form) async {
    return await relationCtrl.user!.cacheObj
        .set('pagetemplatemodule', form.metadata);
  }

  ///加载单位下所有表单
  Future<List<IForm>> loadForms({IApplication? app}) async {
    List<IForm> iForms = [];
    if (null != app) {
      iForms = await app.loadAllForms() ?? [];
    } else {
      // iForms = user?.loadAllForms() ?? [];
    }
    iForms = iForms
        .where((element) => !element.groupTags.contains("已删除"))
        .toSet()
        .toList();
    return iForms;
  }

  ///通过Id获得表单
  Future<IForm?> findFormById(String xformid) async {
    IApplication? app = await findApplication();
    List<IForm> iForms = await relationCtrl.loadForms(app: app);
    IForm? iForm = iForms.firstWhereOrNull((element) => element.id == xformid);
    return iForm ?? iForms.firstOrNull;
  }

  ///获得默认表单
  Future<IForm?> findForm() async {
    IForm? iForm;
    IApplication? app = await findApplication();
    List<IForm> iForms = await loadForms(app: app);
    XForm? cachePages = (await relationCtrl.user!.cacheObj
        .get<XForm>('formmodule.${app?.id}', XForm.fromJson));
    if (cachePages != null) {
      iForm = iForms.firstWhereOrNull((element) => element.id == cachePages.id);
    }
    return iForm ?? iForms.firstOrNull;
  }

  ///设置默认表单
  Future<bool> setForm(IForm form) async {
    IApplication? app = await findApplication();
    // Map<String, dynamic>? cacheForms =
    //     await relationCtrl.user!.cacheObj.get<Map<String, dynamic>>(
    //   'formmodule',
    // );
    // cacheForms ??= {};
    // cacheForms[app?.id ?? ''] = form.metadata;
    return await relationCtrl.user!.cacheObj
        .set('formmodule.${app?.id}', form.metadata);
  }

  void setHomeEnum(HomeEnum value) {
    homeEnum.value = value;
  }

  bool isUserSpace(space) {
    return space == user;
  }

  Future<void> showAddFeatures(ShortcutData item) async {
    if (null != user) {
      switch (item.shortcut) {
        case Shortcut.createCompany:
        case Shortcut.addCohort:
          XDialog.showCreateOrganizationBottomSheet(
            navigatorKey.currentState!.context,
            [item.targetType!],
            headerTitle: item.shortcut.label,
            callBack: (String name, String code, String nickName,
                String identify, String remark, TargetType type) async {
              var target = TargetModel(
                name: name, //nickName,
                code: code,
                typeName: type.label,
                teamName: name,
                teamCode: code,
                remark: remark,
              );
              var data = item.shortcut == Shortcut.createCompany
                  ? await user!.createCompany(target)
                  : await user!.createCohort(target);
              if (data != null) {
                ToastUtils.showMsg(msg: "创建成功");
                return true;
              } else {
                return false;
              }
            },
          );
          break;
        case Shortcut.addPerson:
        case Shortcut.addGroup:
        case Shortcut.addCompany:
          showSearchBottomSheet(
              navigatorKey.currentState!.context, item.targetType!,
              title: item.title, hint: item.hint, onSelected: (targets) async {
            bool success = false;
            if (targets.isNotEmpty) {
              success = await user!.applyJoin(targets);
              if (success) {
                ToastUtils.showMsg(msg: "发送申请成功");
              }
            }
          });
          break;
        case Shortcut.addAppTemp:
          // 应用
          final assetLogic = AssetsManagementLogic.getLogic();
          showSearchApplication(
              navigatorKey.currentState!.context, assetLogic.applications,
              title: "选择应用", hint: "搜索", onSelected: (application) async {
            // assetLogic.currentIndex.value =
            //     assetLogic.applications.indexOf(application[0]);
            // assetLogic.loadWorks();
            await relationCtrl.user!.cacheObj
                .set('assetmodule', application[0].metadata);
          });
          break;
        case Shortcut.addDataTemp:
          // 数据
          List<IForm> iForms = await relationCtrl.loadForms();
          showSearchApplication(navigatorKey.currentState!.context, iForms,
              title: "选择数据", hint: "搜索", onSelected: (selectData) async {
            await relationCtrl.setForm(selectData[0]);
          });
          break;
        case Shortcut.addShareTemp:
          // 共享
          List<IPageTemplate> iPages = await relationCtrl.loadPages();
          showSearchApplication(navigatorKey.currentState!.context, iPages,
              title: "选择共享", hint: "搜索", onSelected: (selectData) async {
            await relationCtrl.user!.cacheObj
                .set('pagetemplatemodule', selectData[0].metadata);
          });
          break;
        case Shortcut.addDealTemp:
          // 交易
          List<IPageTemplate> iPages = await relationCtrl.loadPages();
          showSearchApplication(navigatorKey.currentState!.context, iPages,
              title: "选择交易", hint: "搜索", onSelected: (selectData) async {
            await relationCtrl.user!.cacheObj
                .set('pagetemplatemodule', selectData[0].metadata);
          });
          break;
        case Shortcut.addCustomPage:
          // 定制
          List<IPageTemplate> iPages = await relationCtrl.loadPages();
          showSearchApplication(navigatorKey.currentState!.context, iPages,
              title: "选择定制", hint: "搜索", onSelected: (selectData) async {
            await relationCtrl.user!.cacheObj
                .set('pagetemplatemodule', selectData[0].metadata);
          });
          break;
        default:
      }
    } else {
      ToastUtils.showMsg(msg: "用户信息异常，请重新登陆");
    }
  }

  bool canAutoLogin([List<String>? account]) {
    account ??= Storage.getList(Constants.account);
    if (account.isNotEmpty && account.last != "") {
      return true;
    }
    return false;
  }

  void cancelAutoLogin() {
    Storage.setListValue(Constants.account, 1, "");
  }

  /// 自动登录
  Future<bool> autoLogin([List<String>? account]) async {
    return await syncCall(() async {
      return await _autoLogin(account);
    });
  }

  Future<bool> _autoLogin([List<String>? account]) async {
    account ??= Storage.getList(Constants.account);
    if (!canAutoLogin(account)) {
      exitLogin(false);
      return true;
    }

    try {
      String accountName = account.first;
      String passWord = account.last;
      XLogUtil.d("登陆前Token:${kernel.accessToken}");
      var login = await provider.login(accountName, passWord);
      if (login.success) {
        XLogUtil.d("登陆成功Token:${kernel.accessToken}");
        // Get.offAndToNamed(Routers.logintrans, arguments: true);
        return true;
      } else if (login.code == 401 || login.msg.contains('timeout')) {
        XLogUtil.d("登陆异常Token-401:${kernel.accessToken}");
        await _autoLogin(account);
      } else {
        XLogUtil.d("登陆异常:${login.toJson()}");
        ToastUtils.showMsg(msg: login.msg);
        RoutePages.to(path: Routers.login);
        return false;

        // if (kernel.isOnline) {
        // Future.delayed(const Duration(milliseconds: 100), () async {
        //   await autoLogin();
        // });
        // } else {
        //   kernel.onConnectedChanged((isConnected) {
        //     if (isConnected && null == kernel.user) {
        //       autoLogin();
        //     }
        //   });
        // }
      }
    } catch (e) {
      // if (appStartController.isNetworkConnected) {
      //   return await _autoLogin(account);
      // }
    }
    return false;
  }

  // Future<void> refreshData() async {
  //   await syncCall(() async {
  //     await _refreshData();
  //     return true;
  //   });
  // }

  // Future<void> _refreshData() async {
  //   await provider.refresh();
  // }

  Future<void> refreshToken([List<String>? account]) async {
    await syncCall(() async {
      await _refreshToken(account);
      return true;
    });
  }

  Future<void> _refreshToken([List<String>? account]) async {
    account ??= Storage.getList(Constants.account);
    if (!canAutoLogin(account)) {
      return exitLogin(false);
    }

    try {
      String accountName = account.first;
      String passWord = account.last;
      var res = await provider.refreshToken(accountName, passWord);
      if (res.success) {
        XLogUtil.d("登陆成功Token:${kernel.accessToken}");
        // Get.offAndToNamed(Routers.logintrans, arguments: true);
        return;
      } else if (res.code == 401 || res.msg.contains('timeout')) {
        XLogUtil.d("登陆异常Token-401:${kernel.accessToken}");
        await _autoLogin(account);
      } else {
        XLogUtil.d("登陆异常:${res.toJson()}");
        ToastUtils.showMsg(msg: res.msg);
        RoutePages.to(path: Routers.login);
        return;
      }
    } catch (e) {
      XLogUtil.e(e);
    }
  }

  Future<bool> syncCall(Future<bool> Function() callback) async {
    bool res = true;
    XLogUtil.i(">>>>>刷新token:$_warpUnderwayCount");
    if (_warpUnderwayCount > 0) {
      return res;
    }
    _warpUnderwayCount += 1;
    try {
      res = await callback();
    } catch (e) {}
    _warpUnderwayCount -= 1;
    return res;
  }

  void exitLogin([bool cleanUserLoginInfo = true]) async {
    // if (cleanUserLoginInfo && canAutoLogin()) {
    //   cancelAutoLogin();
    // }
    // if (null != Get.context) {
    //   LoadingDialog.dismiss(navigatorKey.currentState!.context);
    // }
    kernel.stop();
    await HiveUtils.clean();
    homeEnum.value = HomeEnum.door;
    Storage.remove(Constants.loginStatus);
    // Storage.remove(Constants.account);
    // Get.offAllNamed(Routers.login);
    RoutePages.to(path: Routers.login);
  }

  Future<void> qrScan(BuildContext context) async {
    if (null != user) {
      await PermissionUtil.showPermissionDialog(
          navigatorKey.currentState!.context, Permission.camera,
          callback: () async {
        RoutePages.to(path: Routers.scan).then((value) async {
          if (value != null && value != "") {
            if (value.toString().length == 24 &&
                value.toString().indexOf('==') > 0) {
              // RoutePages.to(path: Routers.scanLogin, data: value);
              RoutePages.to(path: Routers.scanLogin, data: value);
            } else if (StringUtil.isJson(value.toString())) {
              RoutePages.to(path: Routers.scanLogin, data: value);
              // RoutePages.to(path: Routers.scanLogin, data: value);
            } else {
              String id = value.toString().split('/').toList().last;
              XEntity? entity = await user!.findEntityAsync(id);
              if (entity != null) {
                List<XTarget> target =
                    await user!.searchTargets(entity.code!, [entity.typeName!]);
                if (target.isNotEmpty) {
                  showQrScanResultModal(context, target[0]);
                  return;
                  // var success = await user!.applyJoin(target);
                  // if (success) {
                  //   ToastUtils.showMsg(msg: "申请发送成功");
                  // } else {
                  //   ToastUtils.showMsg(msg: "申请发送失败");
                  // }
                } else {
                  ToastUtils.showMsg(msg: "获取用户失败");
                }
              }
            }
          }
        });
      });
    } else {
      ToastUtils.showMsg(msg: "用户信息异常，请重新登陆");
    }
  }

  showQrScanResultModal(BuildContext context, XEntity entity) {
    showDialog(
        context: context,
        builder: (context) => Center(
              child: Material(
                  color: Colors.transparent,
                  child: EntityInfoDialog(
                    data: entity,
                  )),
            ),
        barrierColor: Colors.black.withOpacity(0.6));
  }
}

@Deprecated("弃用")
class UserBinding extends Bindings {
  @override
  Future<void> dependencies() async {
    Get.put(IndexController(), permanent: true);
  }
}

enum HomeEnum {
  chat("沟通"),
  work("办事"),
  door("门户"),
  store("数据"),
  relation("关系"),
  setting("设置");

  final String label;

  const HomeEnum(this.label);
}
